# -*- coding: UTF8 -*-

import sys
import lxml.html as H
import urllib2
from PyQt4.QtGui import *
from PyQt4.QtCore import *


class Window(QWidget):
    def __init__(self, parent=None):
        super(self.__class__, self).__init__(parent)
        layout = QVBoxLayout()
        hbox = QHBoxLayout()
        self.edit = QTextEdit()
        self.startBtn = QPushButton("Start")
        self.stopBtn = QPushButton("Stop")
        hbox.addStretch()
        hbox.addWidget(self.startBtn)
        hbox.addWidget(self.stopBtn)
        layout.addWidget(self.edit)
        layout.addLayout(hbox)
        self.setLayout(layout)
        #
        self.work = Worker()
        # SIGNAL&SLOT
        self.startBtn.clicked.connect(self.start)
        self.stopBtn.clicked.connect(self.stop)
        self.connect(self.work, SIGNAL("length"), self.updateUI)
        self.connect(self.work, SIGNAL("finished()"), self.finished)

    def start(self):
        self.work.start()
        self.startBtn.setEnabled(False)

    def updateUI(self, url, length):
        self.edit.append("Url:%s Content:%s" % (url, length))

    def finished(self):
        self.startBtn.setEnabled(True)

    def stop(self):
        self.work.stop()
        self.startBtn.setEnabled(True)


class Worker(QThread):
    def __init__(self, parent=None):
        super(self.__class__, self).__init__(parent)
        self.stoped = False
        self.mutex = QMutex()

    def run(self):
        with QMutexLocker(self.mutex):
            self.stoped = False
        self.url = 'http://blog.sina.com.cn/'
        html = urllib2.urlopen(self.url).read()
        doc = H.document_fromstring(html)
        urlList = doc.xpath('//a/@href')
        for i in range(10):
            url = urlList[i]
        if self.stoped:
            return
        html = urllib2.urlopen(url).read()
        length = len(html)
        self.emit(SIGNAL("length"), url, str(length))
        print 'success'

    def stop(self):
        with QMutexLocker(self.mutex):
            self.stoped = True

    def isStop(self):
        with QMutexLocker(self.mutex):
            return self.stoped


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())